# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, Process, Project, SysProc, Job
from saltops.forms import PaginationForm

def list(req):
    form = PaginationForm(req.GET)
    if not form.is_valid():
        pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']

    jobs = Job.objects.values('jid').distinct()
    result = {'rows': [], 'total': jobs.count()}
    jobs = jobs[offset: offset + limit]
    for job in jobs:
        job = Job.objects.filter(jid = job['jid']).first().parse()
        result['rows'].append(job)
    return JsonResponse(result)

def query(req):
    form = PaginationForm(req.GET)
    if not form.is_valid():
        pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']

    jid = req.GET.get('jid', '')
    jobs = Job.objects.filter(jid = jid)
    result = {'rows': [], 'total': jobs.count()}
    jobs = jobs[offset: offset + limit]
    result['rows'] = [job.parse() for job in jobs]
    return JsonResponse(result)

def delete(req):
    pass

def update(req):
    pass

